package com.birboot.core;

import com.birboot.http.HttpServletRequest;
import com.birboot.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static File baseDir;//类加载路径
    private static File staticDir;//类加载路径下的static目录

    static {
        try {

            //3 发送响应
            baseDir = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());

            //定位累加在路径下的static目录
            staticDir = new File(baseDir, "static");

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws URISyntaxException {
        //2处理请求
        //获取请求的抽象路径
        String str = request.getUri();
        System.out.println(str);

        //将解析请求的细节移动到request构造器中进行
        File file = new File(staticDir, str);


        //判断若读到的文件不为空并且不为目录
        if (file.isFile()) {
            response.setContentFile(file);
        } else {
            response.setA(404);
            response.setStr1("NotFound");
            file = new File(staticDir, "404.html");
            response.setContentFile(file);
        }
    }
}
